from tortoise.expressions import Q

from app.controllers.saas.buckling import buckling_controller
from app.controllers.saas.buckling_todo import buckling_todo_controller
from app.core.crud import CRUDBase
from app.models import Goods, GoodsSku, BucklingGroup, BucklingTodo, Buckling
from app.models.orders import OrdersGoods
from app.schemas.orders import OrdersGoodsCreate,OrdersGoodsUpdate


class OrdersGoodsController(CRUDBase[OrdersGoods, OrdersGoodsCreate, OrdersGoodsUpdate]):
    def __init__(self):
        super().__init__(model=OrdersGoods)

    @staticmethod
    def format_attr(attr):
        names = []
        if attr:
            for attr_item in attr:
                for name in attr_item["attr_value"]:
                    index = attr_item["attr_value"].index(name)  # 获取索引（假设有这个需求）
                    if attr_item["attr_check"][index]:
                        names.append(name)

        # 将所有名字用 `|` 连接起来
        return "|".join(names)

    @staticmethod
    #计算attr的价格
    def format_attr_price(attr):
        price = 0.00
        if attr:
            for attr_item in attr:
                for name in attr_item["attr_value"]:
                    index = attr_item["attr_value"].index(name)  # 获取索引（假设有这个需求）
                    if attr_item["attr_check"][index]:
                        price+=float(attr_item["attr_price"][index])
        return price

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict(exclude_fields=["updated_at","deleted_at"]) for obj in objs]
        ##这里是因为只有sku没有商品信息,所以拿到所有的goods_id
        goods_ids = [good.get('goods_id') for good in data]
        goods_data = await Goods.filter(id__in=goods_ids).values("id", "cover", "name")

        goods_info_dict = {goods['id']: goods for goods in goods_data}
        for item in data:
            goods = goods_info_dict.get(item['goods_id'])
            if goods:
                item['goods_cover'] = goods['cover']
                if item["give_type"] == 1:
                    item['goods_name'] = f"{goods['name']}(自购赠送)"
                elif item["give_type"] == 2:
                    item['goods_name'] = f"{goods['name']}(他购赠送)"
                else:
                    item['goods_name'] = goods['name']
                if item['attr']:
                    item['attr_name'] = self.format_attr(item['attr'])
        return total, data


    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: OrdersGoodsCreate):
        data = await self.create(obj_in=obj_in)
        return data

    async def do_update(self, obj_in: OrdersGoodsUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, search: Q = Q()):
        await self.remove_q(search)
        return True

orders_goods_controller = OrdersGoodsController()
